<?php
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('format', '', 0);
pc_base::load_sys_class('form', '', 0);

class manage extends admin
{

    private $db;

    public $site;

    public $type;

    function __construct()
    {
        parent::__construct();
        pc_base::load_app_func('global');
        $this->db = pc_base::load_model('contest_model'); // 加载model
        $this->siteid = get_siteid(); // 获取当前站点

        $model_setting=pc_base::load_model('site_setting_model');
        $this->type= $model_setting->getValue("contest_type",$this->siteid);
        $this->admin_username = param::get_cookie('admin_username'); // 获取当前登录的管理员
    }

    /**
     * 赛事、活动列表
     */
    public function init()
    {
        $show_dialog = $show_validator = true;
        $show_header = '';
        //区分赛事、活动：is_activity
        if(isset($_GET['is_activity'])&&$_GET['is_activity']==1){
            $where=" is_activity = 1 and ";
            $is_activity=1;
            $column="activity";
            $column_name="活动";
        }else{
            $where = "is_activity = 0 and ";
            $is_activity=0;
            $column_name="赛事";
            $column="contest";
        }
        //组装where语句
        $where .= " status = 1 and siteid =" . $this->siteid;
        //搜索框
        $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';
        $type = isset($_GET['type']) ? $_GET['type'] : '';
        if (isset($_GET['search'])) {
            if ($keyword) {
                if ($type == '1') {
                    $where .= " and `name` LIKE '%$keyword%'";
                } elseif ($type == '2') {
                    $where .= " and `year` LIKE '%$keyword%'";
                } elseif ($type == '3') {
                    $where .= " and `address` like '%$keyword%'";
                }
            }
        }
        //获取分页码
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $contestinfo = $this->db->select($where,"*","", 'end_time DESC , id DESC');#根据 id 降序排列
        $contestinfo=getTreeList($contestinfo,0);
        //获取管理员信息
        $admin_model = pc_base::load_model('admin_model'); // 加载admin_model
        $administrators = $admin_model->getRealnameInfo();
        //数据重构：加上最后编辑者信息
        foreach ($contestinfo as $key=>$value){
            foreach ($administrators as $key2=>$value2){
                if($value['updated_by'] == $key2){
                    $value['publisher'] = $value2;
                    $contestinfo[$key] = $value;
                    break;
                }
            }
        }
       // $pages = $this->db->pages;
        include $this->admin_tpl('contest_list');
    }

    /**
     * 添加赛事、活动
     */
    public function add()
    {
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['begin_time'] = $data['begin_time'];
            $data['end_time'] = $data['end_time']." 23:59:59";
            $data['created_by'] =  $_SESSION['userid'];
            $data['updated_by'] =  $_SESSION['userid'];
            $data['parentid'] =isset($data['parentid'])?$data['parentid']:0;
            $data['is_child'] =isset($data['parentid'])?1:0;
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;
            $result = $this->db->insert($data);
            if ($result) {
                if(isset($data['is_activity'])){
                    $is_activity=$data['is_activity'];
                }else{
                    $is_activity=0;
                }
                $url='?m=contest&c=manage&a=init&is_activity='.$is_activity;
//                if($data['parentid']!=0){
//                    $url.="&id=".$data['parentid'];
//                }
                //记录行为日志
                $log_content = '<span style="color:green;">添加赛事</span>[赛事id：'.$this->db->insert_id().'；赛事名称：'.$_POST['data']['name'].']';
                $this->manage_admin_log($log_content);
                showmessage(L('add_success'), $url);

            } else {
                showmessage(L('add_error'), HTTP_REFERER);
            }
        } else {

            if(isset($_GET['is_activity'])&&$_GET['is_activity']==1){
                $is_activity=1;
                $column="activity";
                $column_name="活动";
            }else{
                $is_activity=0;
                $column_name="赛事";
                $column="contest";
            }
            /*取最新的赛事、活动*/
            $now_contest=$this->db->now_contest_select();
            $show_dialog = $show_validator = true;
            $show_header = '';
            $id = isset($_GET['id']) ? $_GET['id'] :0;
            //  $show_dialog = $show_validator = true;
            pc_base::load_sys_class('format', '', 0);
            pc_base::load_sys_class('form', '', 0);
            include $this->admin_tpl('contest_add');
        }
    }

    /**
     * 编辑赛事、活动
     */
    public function edit()
    {
        //如果没获取到id，则视为非法请求
        $id = isset($_GET['id']) ? $_GET['id'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
        //获取赛事、活动信息
        $data = $this->db->get_one(array(
            'id' => $id
        ));
        $upinfo = $_POST['data'];
        //提交表单
        if (isset($_POST['dosubmit'])) {
            $data = isset($_POST['data']) ? $_POST['data'] : showmessage(L('illegal_parameters'), HTTP_REFERER);
            $data['begin_time'] = $data['begin_time'];
            $data['end_time'] = $data['end_time']." 23:59:59";

            $data['updated_by'] =  $_SESSION['userid'];
            $data['parentid'] =isset($data['parentid'])?$data['parentid']:0;
            $data['is_child'] =isset($data['parentid'])?1:0;

            $data['update_time'] = date("Y-m-d H:i:s",time());
            $data['siteid'] = $this->siteid;
            $data['status'] = 1;
            $result = $this->db->update($data, array(
                'id' => $id
            ));
            if ($result) {
                if(isset($data['is_activity'])){
                    $is_activity=$data['is_activity'];
                }else{
                    $is_activity=0;
                }


                $url='?m=contest&c=manage&a=init&is_activity='.$is_activity;
//                if($data['parentid']!=0){
//                    $url.="&id=".$data['parentid'];
//                }
                //记录行为日志
                $log_content = '<span style="color:blue;">修改赛事</span>[赛事id：'.$id.'；赛事名称：'.$_POST['data']['name'].']';
                $this->manage_admin_log($log_content);
                showmessage(L('edit_success'), $url);

                //showmessage(L('edit_success'), '?m=contest&c=manage&a=init&is_activity='.$is_activity);

            } else {
                showmessage(L('edit_error'), HTTP_REFERER);
            }
        } else {
            if(isset($data['is_activity'])&&$data['is_activity']==1){
                $is_activity=1;
                $column="activity";
                $column_name="活动";
            }else{

                $is_activity=0;
                $column_name="赛事";
                $column="contest";
            }
            $show_dialog = $show_validator = true;
            $show_header = '';
            //$show_dialog = $show_validator = true;
            /*最新的赛事、活动*/
            $now_contest=$this->db->now_contest_select($data['relate_id']);
            $data['begin_time'] = date("Y-m-d",strtotime($data['begin_time']));
            $data['end_time'] = date("Y-m-d",strtotime($data['end_time']));
            include $this->admin_tpl('contest_edit');
        }
    }

    /**
     * 删除、批量删除赛事、活动
     */
    public function del()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $name = $_REQUEST['name'];
        $contest_id = $id;
        $is_activity = $_REQUEST['is_activity'];
        if($is_activity == 1){
            $remindInfo = '当前活动含有子活动，请先删除子活动！';
        }else{
            $remindInfo = '当前赛事含有子赛事，请先删除子赛事！';
        }
        //多个删除
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if($this->db->check_child($v)){
                    showmessage($remindInfo, HTTP_REFERER);
                    return false;
                }

                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        }else{
            //检查该赛事、活动下是否有子赛事、子活动
            if($this->db->check_child($id)){
                showmessage($remindInfo, HTTP_REFERER);
                return false;
            }
        }
        $process_model = pc_base::load_model('contest_process_model'); // 加载contest_process_model
        $award_model = pc_base::load_model('contest_award_model'); // 加载contest_award_model
        $sign_model = pc_base::load_model('contest_sign_model'); // 加载contest_sign_model
        $winner_model = pc_base::load_model('contest_winner_model'); // 加载contest_winner_model
        $source_model = pc_base::load_model('contest_source_model'); // 加载contest_source_model
        $talent_model = pc_base::load_model('contest_talent_model'); // 加载contest_talent_model
        //软删除，更新赛事活动表status字段值为2
        $result = $this->db->update(array(
            'status' => '2'
        ), "id in ('$id')");
        //软删除，更新流程表status字段值为2
        $result2 = $process_model->update(array(
            'status' => '2'
        ), array('contest_id'=>$contest_id));
        //软删除，更新奖项表status字段值为2
        $result3 = $award_model->update(array(
            'status' => '2'
        ), array('contest_id'=>$contest_id));
        //软删除，更新赛事活动报名表status字段值为2
        $result4 = $sign_model->update(array(
            'status' => '3'
        ), array('contest_id'=>$contest_id));
        //软删除，更新获奖者表status字段值为2
        $result5 = $winner_model->update(array(
            'status' => '2'
        ), array('contest_id'=>$contest_id));
        //硬删除，删除赛事活动所关联的资源（1资讯、2视频、3图集）
        $result6 = $source_model->delete(array('contest_id'=>$contest_id));
        //硬删除，删除赛事活动所关联的人才
        $result7 = $talent_model->delete(array('contest_id'=>$contest_id));
        //判断是否都删除成功
        if ($result && $result2 && $result3 && $result4 && $result5 && $result6 && $result7) {
            //记录行为日志
            $log_content = '<span style="color:red;">删除赛事</span>[赛事id：'.$id.'；赛事名称：'.$name.']';
            $this->manage_admin_log($log_content);
            showmessage(L('del_success'), HTTP_REFERER);
        } else {
            showmessage(L('del_error'), HTTP_REFERER);
        }
    }

    /*
     *赛事、活动详情
     **/
    public function view()
    {
        //如果没获取到id，则视为非法请求
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $data = $this->db->get_one(array(
            'id' => $id
        ));
        /*父级信息*/
        if($data['parentid']!=0){
            $parent=$this->db->get_one(array(
                'id' => $data['parentid']
            ));
        }else{
            $parent['name']="";
        }

        $show_dialog = $show_validator = true;
        $show_header = '';
        include $this->admin_tpl('contest_view');
    }
}